﻿using Ops.Mpc.States;
using Ops.Mpc.Models;
using Ops.Mpc.ExampleApplication.DataPaging.Models;
using Ops.Mpc.ExampleApplication.ExampleService;
using System.Collections.Generic;
using Ops.Mpc.Events;
using Ops.Mpc.Collections;
using System.ComponentModel;
using Ops.Mpc.Filters;
using Ops.Mpc.ExampleApplication.Models;
using Ops.Mpc.Ioc;


namespace Ops.Mpc.ExampleApplication.DataPaging.Actions
{
    public class GetPersonsPageStateAction : GetPageAction
    {
        #region Fields
        private DataPagingModel _dataPagingModel = null;
        #endregion 

        public override void Start()
        {
            base.Start();
            _dataPagingModel = this.GetModel<DataPagingModel>();
        }

        protected override void OnExecute(PagerEventArgs pagerEventArgs)
        {
            base.OnExecute(pagerEventArgs);

            this.SetBusyMessage("Loading page {0}",_dataPagingModel.Items.Pager.CurrentPageIndex + 1);

            if (_dataPagingModel != null)
            {
                if (pagerEventArgs.FilterUpdate)
                {
                    List<Filter> filters = new List<Filter>();
                    foreach (SortDescription sortDescription in _dataPagingModel.Items.SortDescriptions)
                        filters.Add(new SortFilter() { PropertyName = sortDescription.PropertyName, SortAscending = sortDescription.Direction == ListSortDirection.Ascending });

                    IocServiceLocator.Get<IExampleServiceContext>().GetPersons(filters.ToArray(), GetPersonsCompleted, OnError);
                }
                else
                    IocServiceLocator.Get<IExampleServiceContext>().GetPersons(pagerEventArgs.Pager, GetPersonsCompleted, OnError);
            }
            else
                this.Finish();

        }

        private void GetPersonsCompleted(Person[] persons, object context)
        {
            _dataPagingModel.Items.FillCurrentPage(persons);

            this.Finish();
        }

        private void GetPersonsCompleted(Pager pager, object context)
        {
            this.Finish();

            _dataPagingModel.Items.Pager = pager;

        }
    }
}
